#include "dialog.h"
#include "ui_dialog.h"
#include "mainwindow.h"

Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) {
  mainWindow = reinterpret_cast<MainWindow *>(parent);
  ui->setupUi(this);
  ui->IP->setFocus();
  connect(ui->OK, SIGNAL(clicked()), this, SLOT(run()));
  connect(this, SIGNAL(destroyed()), mainWindow, SLOT(close()));  // if IP dialog box closes, clean up memory
}

Dialog::~Dialog() {
  delete ui;
}

void Dialog::run() {
  QString IP = ui->IP->text();  // get the IP address the user entered
  if (IP.size() > 0 && valid(IP))
	mainWindow->mainGame(ui->IP->text()); // start the main game loop
  else {
	ui->IP->clear();  // if invalid IP, clear line
	ui->IP->setFocus();
  }
}

// Check if the IP address is valid
bool Dialog::valid(const QString &IP) {
  int length = IP.size();
  if (IP[0] == '.' || IP[length-1] == '.')  // IP address can't start and/or end with a period
	return false;
  int numPeriods = 0;
  int numDigits = 0;
  for (int i = 0; i < length ; i++) {
	if ((IP[i] > '9' || IP[i] < '0') && IP[i] != '.') // if one char is not a valid char then IP address is invalid
	  return false;
	if (IP[i] != '.') { // The above test makes sure that that the current char is valid
	  if (++numDigits > 3)        // can't have more than 3 digits in an octet
		return false;
	}
	if (IP[i] == '.') {
	  if (IP[i+1] == '.') // can't have 2 periods in a row
		return false;
	  numDigits = 0;
	  numPeriods++;
	  if (numPeriods > 3) // if more than 3 periods, then IP address is invalid
		return false;
	}
  }
  if (numPeriods != 3)  //IP has to have 3 periods in between 4 octets.
	return false;
  return true;    // if all the tests pass, then IP address is valid
}
